import type { ResponseData, ResponsePaginationData } from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/request';
import type { RequestData } from '@ant-design/pro-table';
import type {
  AuthPermission,
  AuthRoleAddItem,
  AuthRoleEditItem,
  AuthRoleQueryListParams,
  AuthRoleTableListItem,
  DetailItem,
} from './data';
import { request } from 'umi';
import { message } from 'antd';

type Pagination = { page?: number; pageSize?: number; tenant_id?: string };

export interface AdminRoleListItem {
  id: any;
  name: string;
  accesses?: { id: string; name: string }[];
}

/**
 * 获取账号角色列表
 * @param params
 */
export async function queryAdminRoleList(
  params: Pagination & AuthRoleQueryListParams,
): Promise<RequestData<AuthRoleTableListItem>> {
  const { page = 1, pageSize = 20, name } = params;
  try {
    const res = await request<ResponsePaginationData<AdminRoleListItem>>('/sys/role/list', {
      params: { page, pageSize, name },
    });

    return {
      success: true,
      total: res.data.total,
      data: res.data.list,
    };
  } catch (error) {
    return { code: 1, data: [] };
  }
}

export async function AdminRoleList(
  params: Pagination & AuthRoleQueryListParams,
): Promise<RequestData<AuthRoleTableListItem>> {
  const { tenant_id, name } = params;

  try {
    const res = await request<ResponsePaginationData<AdminRoleListItem>>(
      '/sys/role/get_role_options',
      {
        params: { tenant_id, name },
      },
    );
    return {
      success: true,
      total: res.data.total,
      data: res.data.list,
    };
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    return { code: 1, data: [] };
  }
}

export async function queryUserAdminRolesList(params: {
  userId: string;
}): Promise<RequestData<AuthRoleTableListItem>> {
  if (!params.userId) {
    return {
      success: false,
      total: 0,
      data: [],
    };
  }
  try {
    const res: ResponsePaginationData<{
      id: string;
      name: string;
      code: string;
    }> = await request(`/sys/admin/${params.userId}/roles`, { method: 'GET' });
    return {
      success: res.code === SUCCESS_CODE,
      total: res.data.total,
      data: res.data.list || [],
    };
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    return { code: 1, data: [] };
  }
}

export async function queryAdminRoleDetail(params: {
  id: string;
}): Promise<{ success: boolean; data?: DetailItem }> {
  try {
    const res: ResponseData<DetailItem> = await request(`/sys/role/${params.id}`);

    if (res?.code !== SUCCESS_CODE) {
      return { success: false };
    }

    return {
      success: true,
      data: {
        id: res.data.id,
        name: res.data.name,
        permissions: res.data.permissions,
      },
    };
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    return { data: undefined, success: false };
  }
}

/**
 * 创建一个账号角色
 * @param params
 */
export async function addAdminRole(params: AuthRoleAddItem) {
  try {
    const res = await request('/sys/role/create', {
      method: 'POST',
      data: { name: params.name, permission_ids: params.permissions?.map((o) => o.id) },
    });
    return res;
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    return { code: 1, data: [] };
  }
}

export async function editAdminRole(params: AuthRoleEditItem) {
  const { id, name } = params;
  try {
    const res = await request(`/sys/role/${id}`, { method: 'POST', data: { name } });
    return res;
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    return { code: 1, data: [] };
  }
}

export interface AdminRoleAccessesUpdate {
  roleId: string;
  permissions: AuthPermission[];
}

/**
 * 更新用户角色中的权限配置信息
 *
 * @param params
 */
export async function updateAdminRoleAccesses(
  params: AdminRoleAccessesUpdate,
): Promise<ResponseData<boolean>> {
  const { roleId, permissions } = params;
  const accessIds = permissions?.map((acc) => acc.id);
  try {
    const res = request(`/sys/role/${roleId}/permissions`, { data: { accessIds }, method: 'POST' });
    return res;
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    return {
      code: 1,
      data: false,
      success: false,
      message: '服务器请求失败，请重试，如果多次请求失败，请联系管理员',
    };
  }
}

/**
 * 获取所有可配置权限
 * @param params
 */
export async function fetchConfigurableAuthPermission(
  params: {
    adminId?: string;
  } & Pagination,
): Promise<RequestData<AuthPermission>> {
  const { adminId, page, pageSize } = params;
  try {
    const res: ResponsePaginationData<AuthPermission> = await request(`/sys/permission/list`, {
      params: {
        adminId,
        page,
        pageSize,
      },
    });

    return {
      total: res.data.total,
      success: res.code === SUCCESS_CODE,
      data: res.data.list || [],
    };
  } catch (error) {
    return { code: 1, data: [] };
  }
}

/**
 * 获取某一个角色下的权限列表
 *
 * @param params
 */
export async function queryAdminRoleAccessList(params: {
  roleId: string;
}): Promise<ResponseData<AuthPermission[]>> {
  console.assert(params.roleId, 'roleId is required');
  try {
    const res: ResponseData<AuthPermission[]> = await request(
      `/sys/role/${params.roleId}/permissions`,
    );

    return {
      success: true,
      code: SUCCESS_CODE,
      message: res.message || '没有数据',
      data: res.data || [],
    };
  } catch (error) {
    message.error('服务器请求失败，请重试，如果多次请求失败，请联系管理员');
    return {
      code: 1,
      data: [],
      success: false,
      message: '服务器请求失败，请重试，如果多次请求失败，请联系管理员',
    };
  }
}

export async function removeAdminRole(params: {
  id: string;
}): Promise<ResponseData<AuthPermission[]>> {
  const res: ResponseData<any> = await request(`/sys/role/${params.id}`, { method: 'DELETE' });
  return res;
}
